package com.laundry.merchant.ui.main

import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.laundry.merchant.R
import com.laundry.merchant.databinding.ActivityMainBinding
import com.laundry.merchant.ui.dashboard.DashboardFragment
import com.laundry.merchant.ui.finance.FinanceFragment
import com.laundry.merchant.ui.order.OrderFragment
import com.laundry.merchant.ui.promotion.PromotionFragment
import com.laundry.merchant.ui.ranking.RankingFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityMainBinding
    private val viewModel: MainViewModel by viewModels()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        initViews()
        observeViewModel()
        
        // 默认显示仪表盘
        if (savedInstanceState == null) {
            showFragment(DashboardFragment(), "dashboard")
        }
    }
    
    private fun initViews() {
        setupBottomNavigation()
        setupToolbar()
        setupFab()
    }
    
    private fun setupBottomNavigation() {
        binding.bottomNavigation.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.nav_dashboard -> {
                    showFragment(DashboardFragment(), "dashboard")
                    binding.toolbarTitle.text = "商家中心"
                    true
                }
                R.id.nav_promotion -> {
                    showFragment(PromotionFragment(), "promotion")
                    binding.toolbarTitle.text = "投流管理"
                    true
                }
                R.id.nav_ranking -> {
                    showFragment(RankingFragment(), "ranking")
                    binding.toolbarTitle.text = "排行榜"
                    true
                }
                R.id.nav_order -> {
                    showFragment(OrderFragment(), "order")
                    binding.toolbarTitle.text = "订单管理"
                    true
                }
                R.id.nav_finance -> {
                    showFragment(FinanceFragment(), "finance")
                    binding.toolbarTitle.text = "财务管理"
                    true
                }
                else -> false
            }
        }
    }
    
    private fun setupToolbar() {
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        
        // 设置通知按钮
        binding.notificationButton.setOnClickListener {
            navigateToNotifications()
        }
        
        // 设置设置按钮
        binding.settingsButton.setOnClickListener {
            navigateToSettings()
        }
    }
    
    private fun setupFab() {
        binding.fab.setOnClickListener {
            showQuickActions()
        }
    }
    
    private fun observeViewModel() {
        lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                updateUI(state)
            }
        }
        
        lifecycleScope.launch {
            viewModel.events.collect { event ->
                handleEvent(event)
            }
        }
    }
    
    private fun updateUI(state: MainUiState) {
        // 更新加载状态
        binding.progressBar.visibility = if (state.isLoading) View.VISIBLE else View.GONE
        
        // 更新网络状态
        if (!state.isNetworkAvailable) {
            showNetworkError()
        } else {
            hideNetworkError()
        }
        
        // 更新商家信息
        state.merchantProfile?.let { profile ->
            updateMerchantProfile(profile)
        }
        
        // 更新通知数量
        updateNotificationBadge(state.unreadNotificationCount)
        
        // 更新投流状态
        updatePromotionStatus(state.promotionStatus)
    }
    
    private fun handleEvent(event: MainEvent) {
        when (event) {
            is MainEvent.ShowError -> {
                showError(event.message)
            }
            is MainEvent.NavigateToLogin -> {
                navigateToLogin()
            }
            is MainEvent.ShowPromotionAlert -> {
                showPromotionAlert(event.message)
            }
            is MainEvent.ShowLowBalanceWarning -> {
                showLowBalanceWarning(event.balance)
            }
        }
    }
    
    private fun showFragment(fragment: Fragment, tag: String) {
        val currentFragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
        
        if (currentFragment?.tag == tag) {
            return
        }
        
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment, tag)
            .commit()
    }
    
    private fun updateMerchantProfile(profile: com.laundry.merchant.data.model.MerchantProfile) {
        binding.merchantName.text = profile.name
        binding.merchantRating.text = "⭐ ${profile.rating}"
        
        // 加载商家头像
        com.laundry.merchant.utils.ImageUtils.loadImage(
            binding.merchantAvatar,
            profile.avatar,
            R.drawable.ic_merchant_placeholder
        )
        
        // 更新认证状态
        binding.verifiedBadge.visibility = if (profile.isVerified) View.VISIBLE else View.GONE
    }
    
    private fun updateNotificationBadge(count: Int) {
        if (count > 0) {
            binding.notificationBadge.visibility = View.VISIBLE
            binding.notificationBadge.text = if (count > 99) "99+" else count.toString()
        } else {
            binding.notificationBadge.visibility = View.GONE
        }
    }
    
    private fun updatePromotionStatus(status: PromotionStatus?) {
        status?.let {
            when (it.status) {
                "active" -> {
                    binding.promotionStatusIndicator.setBackgroundColor(
                        androidx.core.content.ContextCompat.getColor(this, R.color.green_500)
                    )
                }
                "paused" -> {
                    binding.promotionStatusIndicator.setBackgroundColor(
                        androidx.core.content.ContextCompat.getColor(this, R.color.orange_500)
                    )
                }
                "stopped" -> {
                    binding.promotionStatusIndicator.setBackgroundColor(
                        androidx.core.content.ContextCompat.getColor(this, R.color.red_500)
                    )
                }
            }
        }
    }
    
    private fun showNetworkError() {
        binding.networkErrorView.visibility = View.VISIBLE
        binding.networkErrorView.setOnClickListener {
            viewModel.retry()
        }
    }
    
    private fun hideNetworkError() {
        binding.networkErrorView.visibility = View.GONE
    }
    
    private fun showError(message: String) {
        com.google.android.material.snackbar.Snackbar.make(
            binding.root,
            message,
            com.google.android.material.snackbar.Snackbar.LENGTH_LONG
        ).show()
    }
    
    private fun showPromotionAlert(message: String) {
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("投流提醒")
            .setMessage(message)
            .setPositiveButton("查看详情") { _, _ ->
                binding.bottomNavigation.selectedItemId = R.id.nav_promotion
            }
            .setNegativeButton("稍后处理", null)
            .show()
    }
    
    private fun showLowBalanceWarning(balance: Double) {
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("余额不足")
            .setMessage("您的推广余额仅剩 ¥${String.format("%.2f", balance)}，请及时充值以免影响推广效果。")
            .setPositiveButton("立即充值") { _, _ ->
                navigateToRecharge()
            }
            .setNegativeButton("稍后充值", null)
            .show()
    }
    
    private fun showQuickActions() {
        val bottomSheet = com.laundry.merchant.ui.common.QuickActionBottomSheet()
        bottomSheet.show(supportFragmentManager, "quick_actions")
    }
    
    private fun navigateToNotifications() {
        val intent = android.content.Intent(this, com.laundry.merchant.ui.notification.NotificationActivity::class.java)
        startActivity(intent)
    }
    
    private fun navigateToSettings() {
        val intent = android.content.Intent(this, com.laundry.merchant.ui.settings.SettingsActivity::class.java)
        startActivity(intent)
    }
    
    private fun navigateToLogin() {
        val intent = android.content.Intent(this, com.laundry.merchant.ui.auth.LoginActivity::class.java)
        startActivity(intent)
        finish()
    }
    
    private fun navigateToRecharge() {
        val intent = android.content.Intent(this, com.laundry.merchant.ui.finance.RechargeActivity::class.java)
        startActivity(intent)
    }
    
    override fun onResume() {
        super.onResume()
        // 检查网络状态
        viewModel.checkNetworkStatus()
        
        // 刷新商家信息
        if (viewModel.isLoggedIn()) {
            viewModel.refreshMerchantProfile()
            viewModel.checkPromotionStatus()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        viewModel.cleanup()
    }
    
    // 提供给Fragment使用的方法
    fun showBottomNavigation() {
        binding.bottomNavigation.visibility = View.VISIBLE
    }
    
    fun hideBottomNavigation() {
        binding.bottomNavigation.visibility = View.GONE
    }
    
    fun showFab() {
        binding.fab.show()
    }
    
    fun hideFab() {
        binding.fab.hide()
    }
    
    fun setToolbarTitle(title: String) {
        binding.toolbarTitle.text = title
    }
}

// UI状态数据类
data class MainUiState(
    val isLoading: Boolean = false,
    val isNetworkAvailable: Boolean = true,
    val merchantProfile: com.laundry.merchant.data.model.MerchantProfile? = null,
    val unreadNotificationCount: Int = 0,
    val promotionStatus: PromotionStatus? = null,
    val error: String? = null
)

// 投流状态数据类
data class PromotionStatus(
    val status: String, // active, paused, stopped
    val balance: Double,
    val dailyBudget: Double,
    val todaySpent: Double,
    val isLowBalance: Boolean
)

// 事件数据类
sealed class MainEvent {
    data class ShowError(val message: String) : MainEvent()
    object NavigateToLogin : MainEvent()
    data class ShowPromotionAlert(val message: String) : MainEvent()
    data class ShowLowBalanceWarning(val balance: Double) : MainEvent()
}
